<template>
  <div class="file-list">
    <div class="file-list-header">
      <el-input
        v-model="searchQuery"
        placeholder="搜索文件名"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><search /></el-icon>
        </template>
      </el-input>

      <div class="filters">
        <el-select v-model="filterType" placeholder="文件类型" clearable>
          <el-option label="DICOM" value="DICOM" />
          <el-option label="NIfTI" value="NIfTI" />
        </el-select>

        <el-select v-model="filterStatus" placeholder="状态" clearable>
          <el-option label="已处理" value="processed" />
          <el-option label="未处理" value="unprocessed" />
        </el-select>

        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </div>
    </div>

    <el-table
      :data="filteredFiles"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column type="expand">
        <template #default="props">
          <el-form label-position="left" inline class="file-detail">
            <el-form-item label="上传时间">
              {{ formatDate(props.row.uploadTime) }}
            </el-form-item>
            <el-form-item label="处理状态">
              {{ props.row.processStatus }}
            </el-form-item>
            <el-form-item label="文件大小">
              {{ formatFileSize(props.row.size) }}
            </el-form-item>
            <el-form-item label="处理时间">
              {{ props.row.processTime || '-' }}
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="文件名" sortable />
      <el-table-column prop="type" label="类型" width="120" />
      <el-table-column prop="uploadTime" label="上传日期" width="180" sortable>
        <template #default="{ row }">
          {{ formatDate(row.uploadTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 'processed' ? 'success' : 'info'">
            {{ row.status === 'processed' ? '已处理' : '未处理' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleLoad(row)">
            加载
          </el-button>
          <el-button type="info" link @click="handleDownload(row)">
            下载
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

interface FileItem {
  id: string
  name: string
  type: string
  size: number
  uploadTime: string
  status: 'processed' | 'unprocessed'
  processTime?: string
  processStatus?: string
}

const searchQuery = ref('')
const filterType = ref('')
const filterStatus = ref('')
const dateRange = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const router = useRouter()

// 模拟文件数据
const files = ref<FileItem[]>([
  {
    id: '1',
    name: 'brain_scan.dcm',
    type: 'DICOM',
    size: 25600000,
    uploadTime: '2024-03-15T10:30:00',
    status: 'processed',
    processTime: '2024-03-15T10:35:00',
    processStatus: '分割完成'
  },
  {
    id: '2',
    name: 'chest_ct.dcm',
    type: 'DICOM',
    size: 158000000,
    uploadTime: '2024-03-15T09:15:00',
    status: 'processed',
    processTime: '2024-03-15T09:20:00',
    processStatus: '分割完成'
  },
  {
    id: '3',
    name: 'spine_mri.nii.gz',
    type: 'NIfTI',
    size: 85000000,
    uploadTime: '2024-03-14T16:45:00',
    status: 'processed',
    processTime: '2024-03-14T16:50:00',
    processStatus: '分割完成'
  },
  {
    id: '4',
    name: 'knee_xray.dcm',
    type: 'DICOM',
    size: 12800000,
    uploadTime: '2024-03-14T14:20:00',
    status: 'unprocessed',
    processStatus: '等待处理'
  },
  {
    id: '5',
    name: 'liver_ct.nii',
    type: 'NIfTI',
    size: 245000000,
    uploadTime: '2024-03-14T11:10:00',
    status: 'processed',
    processTime: '2024-03-14T11:18:00',
    processStatus: '分割完成'
  }
])

// 过滤和搜索逻辑
const filteredFiles = computed(() => {
  return files.value.filter(file => {
    const matchesSearch = file.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesType = !filterType.value || file.type === filterType.value
    const matchesStatus = !filterStatus.value || file.status === filterStatus.value
    const matchesDate = !dateRange.value?.length || isDateInRange(file.uploadTime, dateRange.value)
    
    return matchesSearch && matchesType && matchesStatus && matchesDate
  })
})

// 日期格式化
const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

// 文件大小格式化
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 日期范围检查
const isDateInRange = (date: string, range: string[]) => {
  if (!range || range.length !== 2) return true
  const fileDate = new Date(date)
  const startDate = new Date(range[0])
  const endDate = new Date(range[1])
  return fileDate >= startDate && fileDate <= endDate
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  // 实现搜索逻辑
}

// 加载文件
const handleLoad = async (row: FileItem) => {
  try {
    loading.value = true
    // 从后端API获取体数据
    const response = await fetch(`/api/files/${row.id}/volume`)
    if (!response.ok) {
      throw new Error('Failed to load volume data')
    }
    const volumeData = await response.json()
    
    // 导航到查看器页面并传递数据
    router.push({
      name: 'viewer',
      params: { id: row.id },
      state: { volumeData }
    })
  } catch (error) {
    ElMessage.error('加载影像数据失败')
    console.error('Error loading volume data:', error)
  } finally {
    loading.value = false
  }
}

// 下载文件
const handleDownload = (file: FileItem) => {
  // 实现下载逻辑
  ElMessage.success(`开始下载: ${file.name}`)
}

// 删除文件
const handleDelete = (file: FileItem) => {
  ElMessageBox.confirm(
    `确定要删除文件 ${file.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现删除逻辑
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 重新加载数据
}
</script>

<style scoped>
.file-list {
  padding: 20px;
}

.file-list-header {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.search-input {
  width: 300px;
}

.filters {
  display: flex;
  gap: 10px;
  flex: 1;
}

.file-detail {
  padding: 20px;
}

.el-form--inline .el-form-item {
  margin-right: 40px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style> 